package com.zmn.plat.admin.controller.msg.conf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.pager.LayuiPageUtil;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.common.dto.dept.DeptDRO;
import com.zmn.mcc.common.dto.role.RoleDIO;
import com.zmn.mcc.common.dto.role.RoleDRO;
import com.zmn.mcc.common.dto.staff.StaffDRO;
import com.zmn.plat.common.dictionary.MsgLevelEnum;
import com.zmn.plat.common.dictionary.MsgTypeEnum;
import com.zmn.plat.model.dto.common.TreeGridDTO;
import com.zmn.plat.model.entity.msg.conf.MsgConf;
import com.zmn.plat.model.entity.msg.conf.MsgConfQuery;
import com.zmn.plat.model.entity.msg.receive.role.conf.MsgReceiveRoleConf;
import com.zmn.plat.model.entity.msg.receive.role.conf.MsgReceiveRoleConfQuery;
import com.zmn.plat.model.entity.msg.receive.staff.conf.MsgReceiveStaffConfQuery;
import com.zmn.plat.model.vo.msg.receive.position.conf.OrgPermitTreeVO;
import com.zmn.plat.model.vo.msg.receive.staff.MsgReceiveStaffConfVO;

/**
 * 消息配置表
 *
 * @author linfeng
 * @since 2020-05-18 14:50:14
 */
@Controller
@RequestMapping("/msg/conf/")
public class MsgConfListController extends MsgConfBaseController {

    /**
     * 列表
     *
     * @param query
     * @author linfeng
     * @since 2020-05-18 14:50:14
     */
    @RequestMapping("list")
    @RequiresPermissions("/msg/conf/list.action")
    public ModelAndView list(@ModelAttribute MsgConfQuery query) {

        // 格式化时间选择器时间
        if (!StringUtil.isBlank(query.getCreateStartAndEndDateStr())) {
            String[] strings = LayuiPageUtil.dateIntercept(query.getCreateStartAndEndDateStr());
            query.setCreateStartDate(DateUtil.getDateStart(DateUtil.parse(strings[0], DateUtil.FORMAT_DATE)));
            query.setCreateEndDate(DateUtil.getDateEnd(strings[1], DateUtil.FORMAT_DATE));
        }

        // 格式化时间选择器时间
        if (!StringUtil.isBlank(query.getUpdateStartAndEndDateStr())) {
            String[] strings = LayuiPageUtil.dateIntercept(query.getUpdateStartAndEndDateStr());
            query.setUpdateStartDate(DateUtil.getDateStart(DateUtil.parse(strings[0], DateUtil.FORMAT_DATE)));
            query.setUpdateEndDate(DateUtil.getDateEnd(strings[1], DateUtil.FORMAT_DATE));
        }

        List<MsgConf> items = msgConfService.listPageByQuery(query);

        ModelAndView mav = new ModelAndView("msg/conf/list");
        mav.addObject("items", items);
        mav.addObject("msgTypes", MsgTypeEnum.values());
        mav.addObject("vo", query);
        return mav;
    }

    /**
     * 详情
     *
     * @param msgId
     * @author linfeng
     * @since 2020-05-18 14:50:14
     */
    @RequestMapping("detail")
    @RequiresPermissions("/msg/conf/detail.action")
    public ModelAndView detail(@RequestParam(value = "msgId", defaultValue = "0") Integer msgId) {
        MsgConf msgConf;
        if (msgId == 0) {
            msgConf = new MsgConf();
        } else {
            msgConf = msgConfService.findByKey(msgId);
        }

        ModelAndView mav = new ModelAndView("msg/conf/detail");
        mav.addObject("obj", msgConf);
        mav.addObject("msgTypes", MsgTypeEnum.values());
        mav.addObject("msgLevels", MsgLevelEnum.values());
        mav.addObject("flag", 1);
        return mav;
    }

    /**
     * 消息配置-接受岗位配置页面
     *
     * @param msgId
     * @author linfeng
     * @since 2020-05-19 10:23:38
     */
    @RequestMapping("receive/position")
    @RequiresPermissions("/msg/conf/receive/position.action")
    public ModelAndView position(@RequestParam(value = "msgId", defaultValue = "0") Integer msgId) {
        MsgConf msgConf = msgConfService.findByKey(msgId);
        ModelAndView mav = new ModelAndView("msg/conf/receiveposition");
        mav.addObject("obj", msgConf);
        mav.addObject("flag", 2);
        return mav;
    }

    /**
     * 消息配置-接受岗位配置页面
     *
     * @param msgId
     * @return
     */
    @RequestMapping(value = "receive/position/tree")
    public void tree(HttpServletRequest request, HttpServletResponse response, Integer msgId) {
        List<OrgPermitTreeVO> list = msgReceivePositionConfService.listOrgPermitTreeVOByMsgId(msgId);
        // 封装权限树返回JSON
        TreeGridDTO treeGrid = new TreeGridDTO();
        treeGrid.setData(list);
        treeGrid.setCount(list != null ? list.size() : 0);
        ResponseUtil.outWriteJson(response, JSON.toJSONString(treeGrid));
    }

    /**
     * 消息配置-接受岗位配置页面
     *
     * @param msgId
     * @author linfeng
     * @since 2020-05-19 10:23:38
     */
    @RequestMapping("receive/role")
    @RequiresPermissions("/msg/conf/receive/role.action")
    public ModelAndView role(@RequestParam(value = "msgId", defaultValue = "0") Integer msgId) {
        MsgConf msgConf = msgConfService.findByKey(msgId);

        RoleDIO roleDIO = new RoleDIO();
        roleDIO.setStatus(GlobalConsts.YES);
        ResponseDTO<List<RoleDRO>> data = roleListRemoteService.listByDIO(roleDIO);
        List<RoleDRO> roles = new ArrayList<>();
        if (data.isSuccess()) {
            roles = data.getData();
        }

        MsgReceiveRoleConfQuery msgReceiveRoleConfQuery = new MsgReceiveRoleConfQuery();
        msgReceiveRoleConfQuery.setMsgId(msgId);
        List<MsgReceiveRoleConf> msgReceiveRoleConfs = msgReceiveRoleConfService.listByQuery(msgReceiveRoleConfQuery);
        Map<Integer, Integer> map = new HashMap<>();
        map = msgReceiveRoleConfs.stream().collect(Collectors.toMap(e -> e.getRoleId(), e -> e.getMsgId()));

        ModelAndView mav = new ModelAndView("msg/conf/receiverole");
        mav.addObject("obj", msgConf);
        mav.addObject("items", roles);
        mav.addObject("map", map);
        mav.addObject("flag", 3);
        return mav;
    }

    /**
     * 消息配置-接收信息员工列表页面
     *
     * @param query
     * @author linfeng
     * @since 2020-05-19 11:41:45
     */
    @RequestMapping("receive/staff/list")
    @RequiresPermissions("/msg/conf/receive/staff/list.action")
    public ModelAndView list(@ModelAttribute MsgReceiveStaffConfQuery query) {

        List<MsgReceiveStaffConfVO> items = msgReceiveStaffConfService.listPageByQuery(query);
        if (CollectionUtil.isNotNullOrEmpty(items)) {
            List<Integer> staffIds = items.stream().map(e -> e.getStaffId()).collect(Collectors.toList());
            if (CollectionUtil.isNotNullOrEmpty(staffIds)) {
                ResponseDTO<List<StaffDRO>> responseDTO = staffListRemoteService.listStaffByStaffIds(staffIds, GlobalConsts.YES);
                if (responseDTO.isSuccess()) {
                    Map<Integer, StaffDRO> staffDROMap =
                        responseDTO.getData().stream().collect(Collectors.toMap(item -> item.getStaffId(), item -> item, (p, u) -> p));
                    items.forEach(e -> {
                        e.setRealName(staffDROMap.get(e.getStaffId()) == null ? "" : staffDROMap.get(e.getStaffId()).getRealName());
                        e.setStaffName(staffDROMap.get(e.getStaffId()) == null ? "" : staffDROMap.get(e.getStaffId()).getStaffName());
                        e.setMobile(staffDROMap.get(e.getStaffId()) == null ? "" : staffDROMap.get(e.getStaffId()).getMobile());
                        e.setRoleType(staffDROMap.get(e.getStaffId()) == null ? null : staffDROMap.get(e.getStaffId()).getType());
                        e.setDeptId(staffDROMap.get(e.getStaffId()) == null ? null : staffDROMap.get(e.getStaffId()).getDeptId());
                        e.setDeptOneId(staffDROMap.get(e.getStaffId()) == null ? null : staffDROMap.get(e.getStaffId()).getDeptOneId());
                        e.setDeptTwoId(staffDROMap.get(e.getStaffId()) == null ? null : staffDROMap.get(e.getStaffId()).getDeptTwoId());
                        e.setDeptThreeId(staffDROMap.get(e.getStaffId()) == null ? null : staffDROMap.get(e.getStaffId()).getDeptThrId());
                        e.setStatus(staffDROMap.get(e.getStaffId()) == null ? null : staffDROMap.get(e.getStaffId()).getStatus());
                    });
                }
            }

            ResponseDTO<List<DeptDRO>> deptDros = deptListRemoteService.listDeptByLevelAndStatus(null, GlobalConsts.YES);
            if (deptDros.isSuccess()) {
                Map<Integer, DeptDRO> deptDROMap =
                    deptDros.getData().stream().collect(Collectors.toMap(item -> item.getDeptId(), item -> item, (p, u) -> p));
                items.forEach(e -> {
                    e.setDeptOneName(deptDROMap.get(e.getDeptOneId()) == null ? "" : deptDROMap.get(e.getDeptOneId()).getDeptName());
                    e.setDeptTwoName(deptDROMap.get(e.getDeptTwoId()) == null ? "" : deptDROMap.get(e.getDeptTwoId()).getDeptName());
                    e.setDeptThreeName(deptDROMap.get(e.getDeptThreeId()) == null ? "" : deptDROMap.get(e.getDeptThreeId()).getDeptName());
                });
            }
        }

        ModelAndView mav = new ModelAndView("msg/conf/staff/list");
        mav.addObject("items", items);
        mav.addObject("obj", query);
        mav.addObject("flag", 4);
        return mav;
    }

    /**
     * 跳转到新增接收消息员工页面
     *
     * @param msgId
     * @author linfeng
     * @since 2020-05-18 14:50:14
     */
    @RequestMapping("receive/staff/detail")
    @RequiresPermissions("/msg/conf/receive/staff/detail.action")
    public ModelAndView toAddMsgConfStaff(@RequestParam(value = "msgId", defaultValue = "0") Integer msgId) {
        MsgConf msgConf;
        if (msgId == 0) {
            msgConf = new MsgConf();
        } else {
            msgConf = msgConfService.findByKey(msgId);
        }

        ModelAndView mav = new ModelAndView("msg/conf/staff/detail");
        mav.addObject("obj", msgConf);
        mav.addObject("flag", 4);
        return mav;
    }
}
